﻿//===========================[ 8 / 7 / 2011 LVI ]=============================
//				Copyright c Vitaly Lyaschenko <SkyChameleon@gmail.com>
//								Source file
// Purpose: 
//=============================================================================
#include "cLuaScript.h"

//#ifdef	__cplusplus
extern "C" {
//#endif

#include	"lua.h"
#include	"lualib.h"
#include	"lauxlib.h"

//#ifdef	__cplusplus
};
//#endif

lua_State *LuaVM = NULL;

cLuaScript::cLuaScript()
{
	cwLogger::writeINFO("< Lua VM > Instance Create.");
}

cLuaScript::~cLuaScript()
{
	release();
	cwLogger::writeINFO("< Lua VM > Instance Destroy.");
}

bool cLuaScript::init()
{
	// создание контекста Lua
	LuaVM = luaL_newstate();
	if (LuaVM == NULL)
	{
		cwLogger::writeERROR("Error creating Lua context.\n");
		return false;
	}
	// открытие стандартной библиотеки Lua
	luaL_openlibs ( LuaVM );
	cwLogger::writeINFO("< Lua VM > Initialize Success!");
	return true;
}

void cLuaScript::release()
{
	// закрываем Lua
	lua_close(LuaVM);
}

bool cLuaScript::doScript( const char* fileScript )
{
	// выполненить скрипт из файла
	if ( luaL_dofile( LuaVM, fileScript ) )
	{
		cwLogger::writeERROR( "Error opening script file : " + std::string(fileScript) );
		return false;
	}
	return true;
}

const char* cLuaScript::getGlobalS( const char* field )
{
	lua_getfield( LuaVM, LUA_GLOBALSINDEX, field );
	const char* str = lua_tostring( LuaVM, -1 );
	return str;
}

int cLuaScript::getGlobalI( const char* field )
{
	lua_getfield( LuaVM, LUA_GLOBALSINDEX, field );
	int param = lua_tointeger( LuaVM, -1 );
	return param;
}